package com.atguigu.gmall.activity.controller;

import com.alibaba.nacos.common.util.Md5Utils;
import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.CacheHelper;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.OrderRecode;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import jodd.util.StringUtil;
import org.apache.http.auth.AUTH;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author ：Shine
 * @description：
 * @date ：2021/3/10 23:51
 */
@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @GetMapping("/findAll")
    public Result findAll() {
        return Result.ok(seckillGoodsService.findAll());
    }

    @GetMapping("/getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable Long skuId) {
        return Result.ok(seckillGoodsService.getSeckillGoodsById(skuId));
    }

    @GetMapping("auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request) {
        //    获取用户id，使用md5进行加密，生成下单码,
        String userId = AuthContextHolder.getUserId(request);

        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoodsById(skuId);
        if (seckillGoods != null) {
            //下单码必须在秒杀时间内才可以生成
            Date date = new Date();
            if (DateUtil.dateCompare(seckillGoods.getStartTime(), date) &&
                    DateUtil.dateCompare(date, seckillGoods.getEndTime())) {
                String SkuIdStr = MD5.encrypt(userId);

                return Result.ok(SkuIdStr);
            }
        }
        return Result.fail().message("获取秒杀商品失败");
    }

    @PostMapping("auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId, HttpServletRequest request) {
        //获取验证码并且验证下单码
        String skuIdStr = request.getParameter("skuIdStr");
        String userId = AuthContextHolder.getUserId(request);

        if (!skuIdStr.equals(MD5.encrypt(userId))) {
            //    校验下单吗失败
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }

        //验证状态位
        String status = (String) CacheHelper.get(skuId.toString());
        if (StringUtil.isEmpty(status)) {
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        } else if ("0".equals(status)) {
            //0表示商品已经秒杀完毕
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        } else {
            UserRecode userRecode = new UserRecode();
            userRecode.setSkuId(skuId);
            userRecode.setUserId(userId);
            //    将数据发送到mq进行排队
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER,
                    MqConst.ROUTING_SECKILL_USER, userRecode);

            return Result.ok();
        }

    }

    @GetMapping(value = "auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        return seckillGoodsService.checkOrder(skuId, userId);
    }

    @GetMapping("auth/trade")
    public Result trade(HttpServletRequest request) {
        HashMap<String, Object> result = new HashMap<>();
        //获取登录用户的收货地址
        String userId = AuthContextHolder.getUserId(request);
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);

        //获取订单明细
        OrderRecode orderRecode = (OrderRecode) redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).get(userId);
        if (orderRecode == null) {
            return Result.fail().message("没有找到记录");
        }
        SeckillGoods seckillGoods = orderRecode.getSeckillGoods();

        ArrayList<OrderDetail> detailArrayList = new ArrayList<>();
        //声明一个订单明细，并且进行赋值
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setSkuId(seckillGoods.getSkuId());
        orderDetail.setSkuName(seckillGoods.getSkuName());
        orderDetail.setImgUrl(seckillGoods.getSkuDefaultImg());
        orderDetail.setSkuNum(orderRecode.getNum());
        orderDetail.setOrderPrice(seckillGoods.getCostPrice());
        detailArrayList.add(orderDetail);

        result.put("userAddressList", userAddressList);
        result.put("detailArrayList", detailArrayList);
        // 保存总金额,秒杀一个商品还可以这样写
        // result.put("totalAmount", orderInfo.getTotalAmount());
        result.put("totalAmount", seckillGoods.getCostPrice());
        result.put("totalNum", 1);
        return Result.ok(result);
    }


    @PostMapping("auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));

        //将数据保存到数据库中，原来缓存中有关抢单成功的数据就不要了，记得删除
        Long orderId = orderFeignClient.submitOrder(orderInfo);
        if (orderId == null) {
            return Result.fail().message("下订单失败");
        }
        redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).delete(userId);

        //将真的下单数据保存到缓存中
        redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS_USERS).put(userId, orderId.toString());
        return Result.ok(orderId);
    }
}
